### -*- coding: utf-8 -*- #############################################
# Разработано Паэглит Арвидом (http://keysolutions.ru/)
# Все права защищены, 2007
#
# Developed by Paeglit Arvid (http://keysolutions.ru/)
# All right reserved, 2007
#######################################################################

"""Installation scripts for authentication

$Id: installauthentication.py 39 2007-12-11 13:45:31Z Arvi3D $
"""
__author__  = "Arvid"
__license__ = "KSL"
__version__ = "$Revision: 39 $"
__date__ = "$Date: 2007-12-11 13:45:31 +0000 (Tue, 11 Dec 2007) $"

import re
from zope.app.sqlscript import SQLScript

from ks.cookieclientidmanagerext.cookieclientidmanagerext import CookieClientIdManagerExt
from ks.cookieclientidmanagerext.interfaces import ICookieManagerExt

from zope.app.authentication.authentication import PluggableAuthentication
from zope.app.security.interfaces import IAuthentication

from hivurt.authentication.logincredentials.logincredentials import LoginCredentials
from hivurt.authentication.cookiecredentials.cookiecredentials import CookieCredentials
from hivurt.authentication.authenticator.simpleauthenticator import SimpleAuthenticator

from hivurt.grantstoragesql.mount.mount import MountGrantStorage
from ks.sqltools.simplesqlui.ds.ds import DS
from ks.sqltools.simplesqlui.ds.interfaces import IDS
from ks.sqltools.simplesqlui.factory.factory import Factory
from ks.sqltools.simplesqlui.factory.interfaces import ISqlFactory
from hivurt.authentication.interfaces import IGrantStorage
import hivurt.grantstoragesql.permit.sql

import hivurt.userstoragesql.user.sql
from hivurt.userstoragesql.mount.mount import MountUserStorage
from hivurt.authentication.interfaces import IUserStorage, IExtractCredentials

def installCookieManager(context, **kw):
    """ Install cookieclientidmanagerext"""
    sm = context.getSiteManager()

    sm['CookieClientIdManagerExt'] = CookieClientIdManagerExt()
    cookieManager = sm['CookieClientIdManagerExt']
    cookieManager.namespace = 'ArvidAuth'
    cookieManager.cookieLifetime = 3600
    cookieManager.path = '/'
    sm.registerUtility(cookieManager, provided = ICookieManagerExt)

    return "OK"

def installAuthentication(context, **kw):
    """Устанавливает утилиты для авторизации"""
    sm = context.getSiteManager()

    sm['PluggableAuthentication'] = PluggableAuthentication()
    authutil = sm['PluggableAuthentication']
    sm.registerUtility(authutil, provided = IAuthentication)

    authutil['LoginCredentials'] = LoginCredentials()
    authutil['CookieCredentials'] = CookieCredentials()
    authutil['SimpleAuthenticator'] = SimpleAuthenticator()

    authutil.authenticatorPlugins = ('SimpleAuthenticator', )
    authutil.credentialsPlugins = ('LoginCredentials', 'CookieCredentials')

    return "OK"

#TODO: убрать к чертовой матери, заменить на использование ks.script
SQLSCRIPT_REGEXP = re.compile('^.*<dtml-comment>[\n]*.*connection_id[\s]*:[\s]*(?P<connection_id>[\w\d]+)[\n]*.*arguments[\s]*:[\s]*(?P<arguments>[\w\d\s:<>=\'\"]+)[\n]*.*</dtml-comment>[\n]*(?P<source>(.|\n)*)$')

def getSqlScriptFromSource(source, connection):
    """Возвращает SqlScript из source"""
    res = re.match(SQLSCRIPT_REGEXP, source).groupdict()
    return SQLScript(connectionName=connection,
        source=res['source'], arguments=res['arguments'])

def installGrantStorage(context, database_connection=u"db", **kw):
    """Install grant storage"""
    sm = context.getSiteManager()

    sm['permit'] = DS()
    permit = sm['permit']
    sm.registerUtility(permit, provided = IDS, name = 'permit')

    for key in hivurt.grantstoragesql.permit.sql.all:
        permit[key] = getSqlScriptFromSource(getattr(hivurt.grantstoragesql.permit.sql, key), database_connection)


    sm['permitFactory'] = Factory()
    permitFactory = sm['permitFactory']
    permitFactory.ids = (u'code', )
    permitFactory.datasource = u'permit'
    permitFactory.factory = u'Permit'
    sm.registerUtility(permitFactory, provided = ISqlFactory, name = 'permit')

    sm['mount_permit'] = MountGrantStorage(datasource = 'permit', factory = 'permit', isactivated = True)
    mount_permit = sm['mount_permit']
    mount_permit.maxpermit = 3
    mount_permit.ttl = 3600
    sm.registerUtility(mount_permit, provided = IGrantStorage, name = '')

    return "OK"

def installUserStorage(context, database_connection=u"db", **kw):
    """Install user storage"""
    sm = context.getSiteManager()

    sm['principal'] = DS()
    principal = sm['principal']
    sm.registerUtility(principal, provided = IDS, name = 'principal')

    for key in hivurt.userstoragesql.user.sql.all:
        principal[key] = getSqlScriptFromSource(getattr(hivurt.userstoragesql.user.sql, key), database_connection)


    sm['principalFactory'] = Factory()
    principalFactory = sm['principalFactory']
    principalFactory.ids = (u'id', )
    principalFactory.datasource = u'principal'
    principalFactory.factory = u'Principal'
    sm.registerUtility(principalFactory, provided = ISqlFactory, name = 'principal')

    sm['mount_principal'] = MountUserStorage(datasource = 'principal', factory = 'principal', isactivated = True)
    userstorage = sm['mount_principal']
    sm.registerUtility(userstorage, provided = IUserStorage, name = '')
    sm.registerUtility(userstorage, provided = IExtractCredentials, name = '')

    return "OK"

def installSMTPChannelAndTemplate(context, **kw):

    from ks.mailer.interfaces import ITemplateAdaptable
    from zope.app.zptpage import ZPTPage
    from ks.channelsmtp.channelsmtp import ChannelSMTP
    from ks.channelsmtp.interfaces import IChannelSMTP
    from ks.mailersmtp.interfaces import IMailerSMTP
    import arvidcfg.install.root.addprincipal

    sm = context.getSiteManager()
    obj = ZPTPage()
    obj.source = getattr(arvidcfg.install.root.addprincipal, 'AddPrincipalSMTPTemplate')
    sm['AddPrincipalSMTPTemplate'] = obj
    sm.registerUtility(sm['AddPrincipalSMTPTemplate'], provided=ITemplateAdaptable,
        name='AddPrincipalSMTPTemplate')

    obj = ChannelSMTP()
    sm['AddPrincipalSMTPChannel'] = obj
    sm['AddPrincipalSMTPChannel'].delivery = u'mail-delivery'
    sm['AddPrincipalSMTPChannel'].fromAddress = kw['back_email']
    obj = IMailerSMTP(sm['AddPrincipalSMTPChannel'])
    obj.mime = 'text/plain'
    obj.template = 'AddPrincipalSMTPTemplate'
    obj.Subject = u'Успешная регистрация на "%(site)s"'
    obj.mail_header = u'Поздравляем!!! \n__________________\n'
    obj.mail_footer = u'__________________ \nРобот "%(site)s"'
    sm.registerUtility(sm['AddPrincipalSMTPChannel'], provided=IChannelSMTP,
        name='AddPrincipalSMTPChannel')

    return "OK"

#def installPrincipalSource(context, **kw):
#    from arvidcontent.principalsource.install.install import installPrincipalSource
#    return installPrincipalSource(context, **kw)
